package com.yyaccp.easybuy.security.service.token;

import com.yyaccp.easybuy.security.vo.LoginUser;
import com.yyaccp.easybuy.security.vo.Token;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.util.StringUtils;

import java.util.UUID;
import java.util.concurrent.TimeUnit;

public class TokenServiceRedisImpl implements TokenService {
    @Autowired
    private RedisTemplate redisTemplate;

    @Override
    public Token createToken(LoginUser loginUser) {
        String uuid = UUID.randomUUID().toString();
        redisTemplate.opsForValue().set(uuid, loginUser, 30, TimeUnit.MINUTES);
        Token token = new Token(uuid, loginUser.getUsername(), System.currentTimeMillis(), System.currentTimeMillis() + 1800*1000);
        return token;
    }

    @Override
    public LoginUser getLoginUser(String token) {
        LoginUser loginUser = (LoginUser) redisTemplate.opsForValue().get(token);
        return loginUser;
    }

    @Override
    public void deleteToken(String token) {
        if(StringUtils.hasText(token)) {
            redisTemplate.delete(token);
        }
    }
}
